package qingxin.servlet.admin.album;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import qingxin.dao.AlbumDAO;
import qingxin.dao.PhotoDAO;
import qingxin.factory.DAOFactory;
import qingxin.servlet.admin.AdminServlet;
import qingxin.vo.Album;

@WebServlet("/admin/album/edit")
public class EditServlet extends AdminServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private AlbumDAO albumDAO;
	private PhotoDAO photoDAO;
	public EditServlet(){
		super();
		albumDAO = DAOFactory.getAlbumDAO();
		photoDAO = DAOFactory.getPhotoDAO();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		if(!verification(request)){
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			return;
		}
		
		try{
			int albumID = Integer.parseInt(request.getParameter("aid"));
			
			albumDAO.delete(albumID);
			
			String albumS = request.getParameter("album");
			JSONObject jsonAlbum = new JSONObject(albumS);
			
			Album album = new Album();
			album.setCoverID(jsonAlbum.getInt("cover"));
			album.setIntroduction(jsonAlbum.getString("introduction"));
			album.setName(jsonAlbum.getString("name"));
			
			albumDAO.add(album);
			
			JSONArray photos = jsonAlbum.getJSONArray("photos");
			JSONArray descriptions = jsonAlbum.getJSONArray("descriptions");
			JSONArray photographers = jsonAlbum.getJSONArray("photographers");
			for(int i = 0; i < photos.length(); i++){
				photoDAO.updateAlbumID(photos.getInt(i), album.getAlbumID());
				photoDAO.updateDescription(descriptions.getString(i), photos.getInt(i));
				photoDAO.updatePhotographer(photographers.getString(i), photos.getInt(i));
			}
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
}
